package com.platform.server.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.conn.ConnectTimeoutException;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.paltform.server.entity.ExceIRecomUser;
import com.paltform.server.entity.ExceIWithdraw;
import com.paltform.server.entity.SysUser;
import com.platform.server.dao.UserDao;
import com.platform.server.dao.WithdrawDao;
import com.platform.server.service.WithdrawService;
import com.platform.server.util.ExportExcel;
import com.platform.server.util.HttpClientUtils;
import com.platform.server.util.ReturnResult;
import com.platform.server.util.WxpayDemoUtils;
import com.szrca.ima.utils.StringTools;

@Controller
public class WithdrawController {

	@Autowired
	private WithdrawService withdrawService;
	
	@Autowired
	private WithdrawDao withdrawDao;
	
	/**
	 * 提现审核列表
	 */
	@RequestMapping("/selectWithdrawList")
	public Object selectWithdrawList(HttpServletRequest request,String id,String state,String startTime,String endTime,String mobile,String address,String type){
		if("请选择分类".equals(state)){
			state = null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String, Object>> lists = withdrawService.selectWithdrawList(id, state, startTime, endTime, mobile, address, type);
		for(int i = 0;i < lists.size();i++){
			lists.get(i).put("create_time",sdf.format(lists.get(i).get("create_time")));
		}
		request.setAttribute("lists", lists);
		request.setAttribute("nums",lists.size());
		if(!StringTools.isEmpty(id)){
			request.setAttribute("data", lists.get(0));
			return "/ui/withdraw/withdraw_info.jsp";
		}
		return "/ui/withdraw/withdraw_list.jsp";
	}
	
	  /**
		 * 修改审核状态
		 * @throws UnsupportedEncodingException 
	 * @throws JSONException 
		 */
		@RequestMapping("/batchWithdrawStatus")
		public void batchWithdrawStatus(HttpSession session,HttpServletRequest request,HttpServletResponse response, String username,String idd, String states,String userid,String money,String orderId) throws Exception{
			SysUser su = (SysUser) session.getAttribute("user");
			int flag=0;
			String user = null;
			if(su != null){
				user = su.getSys_name();
			}
			
			//增加操作日志记录
			String content = null;
			if("审核通过".equals(states)){
				Map<String, Object> maps = withdrawDao.queryUserMoney(userid);
				BigDecimal totalMoney = new BigDecimal(maps.get("money").toString());
				if (totalMoney.compareTo(new BigDecimal(money)) >= 1 || totalMoney.compareTo(new BigDecimal(money)) == 0) {
					totalMoney = totalMoney.subtract(new BigDecimal(money));
				/*	Map<String,Object> map = new HashMap<>();
					map.put("userid", userid);
					map.put("money", Double.valueOf(money));
					withdrawDao.insertUserWallet(map);*/
					Map<String, String> params = new HashMap<>();
					params.put("id", idd);
					params.put("token", "HuaTianXiaWithdraw");
					String url = "http://hanya.htx328.com/hua-tianxia/wallet/autoWithdraw";
					try {
						HttpClientUtils.postParameters(url, params);
					} catch (ConnectTimeoutException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (SocketTimeoutException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					//withdrawDao.insertAllCancelOrder(userid, money.toString(), "提现成功",orderId,totalMoney.toString());
					 flag = withdrawService.updateWithdrawStatus(Integer.parseInt(idd), states,su.getSys_name());
					content = "审核通过了" + username + "的提现申请";
				}else{
					flag = withdrawService.updateWithdrawStatus(Integer.parseInt(idd), "审核不通过",su.getSys_name());
					content = "没有通过" + username + "的提现申请";
				}
			}else if("审核不通过".equals(states)){
				content = "没有通过" + username + "的提现申请";
				flag =withdrawService.updateWithdrawStatus(Integer.parseInt(idd), states,su.getSys_name());
				//添加消息表记录，提现失败
				withdrawDao.insertMessqge(userid,"你发起的提现失败，请重新提交", "6", idd);
			/*	Map<String,Object> map = new HashMap<>();
				map.put("userid", userid);
				map.put("money", Double.valueOf(money));
				withdrawDao.insertUserWallet(map);
				withdrawDao.insertCancelOrder(userid, money, "提现失败",WxpayDemoUtils.getRandomString(16));
				*/
				Map<String, Object> selectById = withdrawDao.selectById(Integer.valueOf(idd));
				if (!selectById.isEmpty()) {
					String withdrawal_order = selectById.get("withdrawal_order").toString();	
					withdrawDao.deleteCancelOrder(withdrawal_order);
					withdrawDao.insertCancelOrder(userid, money, "提现失败(后台审核失败)",withdrawal_order);			
				}
			}
			withdrawDao.insertLog(user, content);
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("flag", flag);
	        response.getOutputStream().write(jsonObject.toString().getBytes("utf-8"));
		}
	/**
	 * 修改审核状态
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/updateWithdrawStatus")
	public Object updateWithdrawStatus(HttpSession session,HttpServletRequest request,String username,String idd, String states,String userid,String money,String orderId,HttpServletResponse response) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		
		SysUser su = (SysUser) session.getAttribute("user");
		String user = null;
		if(su != null){
			user = su.getSys_name();
		}
	/*	if("提现到账".equals(states)){
			states = "提现完成";
		}
		//int flag = withdrawService.updateWithdrawStatus(Integer.parseInt(idd), states);
		//增加消息表记录
		if("提现完成".equals(states)){
			withdrawDao.insertMessqge(userid,"你发起的提现已经到账", "3", idd);
			//减少用户钱包金额
			Map<String,Object> map = new HashMap<>();
			map.put("userid", userid);
			map.put("money", Double.parseDouble(money));
			withdrawDao.updateUserWallet(map);
		}*/
		//增加操作日志记录
		String content = null;
		if("审核通过".equals(states)){
			Map<String, Object> maps = withdrawDao.queryUserMoney(userid);
			BigDecimal totalMoney = new BigDecimal(maps.get("money").toString());
			if (totalMoney.compareTo(new BigDecimal(money)) >= 1 || totalMoney.compareTo(new BigDecimal(money)) == 0) {
				totalMoney = totalMoney.subtract(new BigDecimal(money));
				/*Map<String,Object> map = new HashMap<>();
				map.put("userid", userid);
				map.put("money", Double.valueOf(money));
				withdrawDao.insertUserWallet(map);*/
				Map<String, String> params = new HashMap<>();
				params.put("id", idd);
				params.put("token", "HuaTianXiaWithdraw");
				String url = "http://hanya.htx328.com/hua-tianxia/wallet/autoWithdraw";
				try {
					String data = HttpClientUtils.postParameters(url, params);
			        ReturnResult parseObject = com.alibaba.fastjson.JSONObject.parseObject(data, ReturnResult.class);
			        if(parseObject!=null){
			        	if(parseObject.getCode()==200){
			        		//withdrawDao.insertAllCancelOrder(userid, money.toString(), "提现成功",orderId,totalMoney.toString());
							withdrawService.updateWithdrawStatus(Integer.parseInt(idd), states,su.getSys_name());
							content = "审核通过了" + username + "的提现申请";
							System.out.println(data);
			        	}
			        }
				} catch (ConnectTimeoutException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SocketTimeoutException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}else{
				withdrawService.updateWithdrawStatus(Integer.parseInt(idd), "审核不通过",su.getSys_name());
				content = "没有通过" + username + "的提现申请";
			}
		}else if("审核不通过".equals(states)){
			content = "没有通过" + username + "的提现申请";
			withdrawService.updateWithdrawStatus(Integer.parseInt(idd), states,su.getSys_name());
			//添加消息表记录，提现失败
			withdrawDao.insertMessqge(userid,"你发起的提现失败，请重新提交", "6", idd);
		/*	Map<String,Object> map = new HashMap<>();
			map.put("userid", userid);
			map.put("money", Double.valueOf(money));
			withdrawDao.insertUserWallet(map);	
			*/
			Map<String, Object> selectById = withdrawDao.selectById(Integer.valueOf(idd));
			if (!selectById.isEmpty()) {
				String withdrawal_order = selectById.get("withdrawal_order").toString();
				
			    withdrawDao.deleteCancelOrder(withdrawal_order);
				withdrawDao.insertCancelOrder(userid, money, "提现失败(后台审核失败)",withdrawal_order);			
			}
		
		}else if("提现完成".equals(states)){
			content = "完成了" + username + "的提现到账";
		}
		withdrawDao.insertLog(user, content);
		return "/selectWithdrawList";
	}
	// 导出报表
	@RequestMapping("/withdrawExportExcel")
	public void exportExcelInInvoice1(HttpServletResponse response, HttpServletRequest request,String id,String state,String startTime,String endTime,String mobile,String address,String type){
		if("请选择分类".equals(state)){
			state = null;
		}
		List<Object> list2 = new ArrayList<Object>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Map<String, Object>> lists = withdrawService.selectWithdrawList(id, state, startTime, endTime, mobile, address, type);
		for(int i = 0;i < lists.size();i++){
			lists.get(i).put("create_time",sdf.format(lists.get(i).get("create_time")));
		}
		for(Map<String, Object> user:lists){
			ExceIWithdraw withdraw = new ExceIWithdraw();
			withdraw.setUsername(user.get("username"));
			withdraw.setMobile(user.get("mobile"));
			withdraw.setRealName(user.get("real_name"));
			withdraw.setId(user.get("id"));
			withdraw.setMoney(user.get("money"));
			if(user.get("type").equals("1")){
				withdraw.setType("银行卡提现");
			}else if(user.get("type").equals("2")){
				withdraw.setType("支付宝提现");
			}
			withdraw.setBankCard(user.get("bank_card"));
			withdraw.setBankName(user.get("bank_name"));
			withdraw.setCreateTime(user.get("create_time"));
			withdraw.setState(user.get("state"));
			list2.add(withdraw);
		}
		String[] titles = {"姓名" , "手机号" , "真实姓名" , "提现单号" , "提现金额" ,  "提现类型" , "提现账号" , "银行卡类型" , "提交时间" , "审核状态"};
		ExportExcel.exportExcel("提现审核表.xls", titles, list2, response);
	}
	
}
